import { defineStore } from "pinia";
import { ref } from "vue";
import { computed } from "vue";
export const useCartStore = defineStore("cart", () => {
  //state
  const cartlist = ref([]);
  //action
  const getCartList = (sku) => {
    const res = cartlist.value.find((item) => sku.skuId === item.skuId);
    if (res) {
      res.count++;
    } else {
      cartlist.value.push(sku);
    }
  };
  const delCart = (id) => {
    const index = cartlist.value.findIndex((item) => {
      id === item.skuId;
    });
    cartlist.value.splice(index, 1);
  };
  //计算总价
  const Allprice = computed(() =>
    cartlist.value.reduce((a, c) => a + c.price * c.count, 0)
  );
  //总数
  const Allcount = computed(() =>
    cartlist.value.reduce((a, c) => a + c.count, 0)
  );
  return { cartlist, getCartList, delCart, Allprice, Allcount };
});
